package com.retail.shopping.server.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.retail.common.core.domain.Result;
import com.retail.shopping.common.domain.ShoppingCart;
import com.retail.shopping.common.domain.request.CartInsertRequest;
import com.retail.shopping.common.domain.response.CartListResponse;
import com.retail.shopping.server.service.IShoppingCartService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.retail.shopping.server.mapper.ShoppingCartMiddenMapper;
import com.retail.shopping.common.domain.ShoppingCartMidden;
import com.retail.shopping.server.service.IShoppingCartMiddenService;

/**
 * 购物车列表Service业务层处理
 * 
 * @author retail
 * @date 2024-02-27
 */
@Service
public class ShoppingCartMiddenServiceImpl implements IShoppingCartMiddenService 
{
    @Autowired
    private ShoppingCartMiddenMapper shoppingCartMiddenMapper;




    private static final Logger log = LoggerFactory.getLogger (IShoppingCartMiddenService.class);


    /**
     * 查询购物车列表列表
     */
//    @Override
//    public Result<List<CartListResponse>> selectShoppingCartMiddenList(Integer userId)
//    {
//        //这里后续可以改成redis现在只是一个简单的效果
//        //购物车列表
//        //获取用户对应的购物车Id
//        ShoppingCart cart = iShoppingCartService.selectShoppingFindByUserId (userId);
//        if(cart!=null){
//
//            //联查购物车商品信息表
//            String str="";
//            List<CartListResponse> CartList =shoppingCartMiddenMapper.selectCartList(cart.getCartId ());
//            for (CartListResponse cartListResponse : CartList) {
//                if(cartListResponse.getProductCount ()<cartListResponse.getSkuNum () && 0>=cartListResponse.getProductCount ()){
//                    str+=","+cartListResponse.getMiddenId ();
//                }
//            }
//            if(str.length ()>0){
//                str.substring (1);
//                shoppingCartMiddenMapper.updCart(str);
//            }
//
//            return Result.success (CartList);
//        }
//        //获取失败
//        //这里的一个返回错误值可以使用统一异常类
//        return Result.error ("获取购物车信息失败");
//    }
    @Autowired
    private IShoppingCartService iShoppingCartService;

    @Autowired
    private  RedisTemplate<String,String> redisTemplate;

    private String redisKey = "SHOPPING_CART:CART_USER_ID_";


    @Override
    public Result<List<CartListResponse>> selectShoppingCartMiddenList(Integer userId) {
        // 判断Redis中是否存在该购物车信息
        String key =redisKey+userId;
        BoundHashOperations<String, Object, Object> carMap = redisTemplate.boundHashOps (key);
        List<Object> cartLists = carMap.values ();
        List<CartListResponse> items = new ArrayList<> ();
        if(CollectionUtils.isNotEmpty (cartLists)){
            cartLists.forEach (item->{
                String ObjItem = (String)item;
                CartListResponse cartListResponse = JSON.parseObject (ObjItem, CartListResponse.class);
                items.add (cartListResponse);
            });
            return Result.success (items);
        }
        // 从数据库中获取购物车信息
        ShoppingCart cart = iShoppingCartService.selectShoppingFindByUserId(userId);
        if (cart != null) {
            // 联查购物车商品信息表
            List<CartListResponse> cartList = shoppingCartMiddenMapper.selectCartList(cart.getCartId());
            // 将购物车列表存入Redis的Hash结构中
            // hash[id:map:[string,object]]
            // 更新购物车信息同时新增到Redis中的Hash结构
            String str = "";
            for (CartListResponse cartListResponse : cartList) {
                if (cartListResponse.getProductCount() < cartListResponse.getSkuNum() && cartListResponse.getProductCount() <= 0) {
                    str += "," + cartListResponse.getMiddenId();
                }
                carMap.put (cartListResponse.getSkuId ()+"",JSON.toJSONString (cartListResponse));
            }

            if (str.length() > 0) {
                str = str.substring(1);
                shoppingCartMiddenMapper.updCart(str);
            }

            return Result.success(cartList);
        }
        // 获取失败
        // 这里的一个返回错误值可以使用统一异常类
        return Result.error("获取购物车信息失败");
    }


    @Override
    public ShoppingCartMidden selectCartMidden(CartInsertRequest cartInsertRequest) {
        return shoppingCartMiddenMapper.selectCartMidden(cartInsertRequest);
    }

    @Override
    public void updateCartMidden(CartInsertRequest cartInsertRequest) {
        shoppingCartMiddenMapper.updateCartMidden (cartInsertRequest);
    }

    @Override
    public void insertCartMidden(CartInsertRequest cartInsertRequest) {
        //新增sku购物车
        shoppingCartMiddenMapper.insertCartMidden(cartInsertRequest);
    }

    @Override
    public void deleteCartMiddenBySkuUser(Integer userId, String str) {
        String key = redisKey+userId;
        BoundHashOperations<String, Object, Object> cartMap = redisTemplate.boundHashOps (key);
        if(str.length ()>=1){
            String[] split = str.split (",");
            for (String s : split) {
                cartMap.delete (s);
            }
        }else{
            cartMap.delete (str);
        }
        ShoppingCart shoppingCart = iShoppingCartService.selectShoppingFindByUserId (userId);
        shoppingCartMiddenMapper.deleteCartMiddenBySkuUser(shoppingCart.getCartId (),str);

    }

    @Override
    public  Map<Integer, Map<ShoppingCart, List<CartListResponse>>> selectCartMergerBathchList(ArrayList<ShopCartBatchService.CartMergeRequest> cartReqs) {

        //map<Integer,List>
        List<Integer> userIds = cartReqs.stream().map(ShopCartBatchService.CartMergeRequest::getUserId).collect(Collectors.toList());
        List<ShoppingCart> carts = iShoppingCartService.selectShopCartFindByUserId(userIds);

        List<Integer> cartIds = carts.stream().map(ShoppingCart::getCartId).collect(Collectors.toList());

        List<CartListResponse> cartList = shoppingCartMiddenMapper.selectCartMergeList(cartIds);

        // 对购物车数据进行分组
        Map<Integer, List<CartListResponse>> cartListResponseMap = cartList.stream()
                .collect(Collectors.groupingBy(CartListResponse::getCartId));

        // 构建最终的 Map<ShoppingCart, List<CartListResponse>
        Map<Integer, Map<ShoppingCart, List<CartListResponse>>> finalMap = new HashMap<>();

        // 遍历每个用户ID
        for (Integer userId : userIds) {
            Map<ShoppingCart, List<CartListResponse>> userCartMap = new HashMap<>();

            // 根据用户ID匹配对应的购物车数据
            for (ShoppingCart cart : carts) {
                if (cart.getUserId().equals(userId)) {
                    List<CartListResponse> cartListResponses = cartListResponseMap.get(cart.getCartId());
                    if (cartListResponses != null) {
                        userCartMap.put(cart, cartListResponses);
                    }
                }
            }

            // 将匹配的结果放入最终的Map中
            finalMap.put(userId, userCartMap);
        }

        return finalMap;
    }
}
